import itchat
from apscheduler.schedulers.blocking import BlockingScheduler
from itchat.content import INCOME_MSG

from commons.log import LogFactory
from filter.blocked_room_filter import BlockedRoomFilter
from service.contact_service import monitor_contacts, SocialNetworkService, ContactService
from service.login_service import qr_callback, login_callback, exit_callback
from wbot.message_action import process_msg
from wbot.settings import PKL_PATH

logger = LogFactory("wechat").get_logger()
scheduler = BlockingScheduler()


@itchat.msg_register(INCOME_MSG, isFriendChat=True)
def friend_chat(msg):
    # 个人消息
    process_msg(msg)


@itchat.msg_register(INCOME_MSG, isGroupChat=True)
def group_chat(msg):
    # 群组消息
    process_msg(msg, True)


@itchat.msg_register(INCOME_MSG, isMpChat=True)
def mp_chat(msg):
    # 公众号消息
    process_msg(msg)


itchat.auto_login(hotReload=True,
                  statusStorageDir=PKL_PATH,
                  qrCallback=qr_callback,
                  loginCallback=login_callback,
                  exitCallback=exit_callback)

itchat.run(blockThread=False)


@scheduler.scheduled_job('cron', hour=2)
def contact_refrash():
    logger.info("保存联系人")
    monitor_contacts()


@scheduler.scheduled_job('cron', hour=6)
def sn_refrash():
    logger.info("分析群聊成员变化")
    service = SocialNetworkService()
    service.analyse_group()


if __name__ == '__main__':
    # 尽量早初始化各单例类的实例
    ContactService()
    SocialNetworkService()
    BlockedRoomFilter()
    logger.info("各组件初始化完毕")
    
    scheduler.start()
